package com.fz.security.utils;

import com.fz.entity.system.User;
import com.fz.security.config.SecurityProperties;
import com.fz.utils.JacksonUtils;
import com.fz.utils.RedisUtil;
import com.fz.utils.SpringContextUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;


public class SecurityUtils {

    /**
     * @方法描述:  获取当前用户信息
     * @参数:
     * @返回值:
     * @创建人: I am God
     * @创建时间:: 2021/3/18
     */
    public static User getCurrentUser(){
        //只获取用户的基本信息即可 所以将用户信息转为了User对象
        User user = new User();
        RedisUtil redisUtil = SpringContextUtil.getBean(RedisUtil.class);
        Object object = redisUtil.get(getToken());
        if(object != null){
            user = JacksonUtils.string2Obj(JacksonUtils.obj2String(object), User.class);
        }
        return user;
    }

    /**
     * @方法描述: 用于获取当前用户授权信息，并不提供用户信息 -- 用于进行按钮权限认证
     * @参数:
     * @返回值:
     * @创建人: I am God
     * @创建时间:: 2021/3/18
     */
    public static UserDetails getUserDetails() {
        UserDetails  userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userDetails;
    }

    /**
     * @方法描述: 获取当前用户的token , 去除Token 前缀 Bearer
     * @参数:
     * @返回值:
     * @创建人: I am God
     * @创建时间:: 2021/3/18
     */
    public static String getToken() {
        SecurityProperties properties = SpringContextUtil.getBean(SecurityProperties.class);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        final String requestHeader = request.getHeader(properties.getHeader());
        if (requestHeader != null && requestHeader.startsWith(properties.getTokenStartWith())) {
            return requestHeader.substring(7);
        }
        return null;
    }
}
